#include "freeregex.h"

#define VERSION "freeregex 0.1"

static void parse_options(int argc, char **argv);
static void usage();
static void version();

static char *regex_str;
static char *regex_src;
extern int errno;


int main(int argc, char **argv)
{
	regex_t *preg = NULL;
	parse_options(argc, argv);
	if( !regex_str || !regex_src) {
		fprintf(stderr, "regex char %p, or regex source %p\n", regex_str, regex_src);
		return 1;
	}
	fprintf(stderr, "pattern: %s\nsource: %s\n", regex_str, regex_src);
	if((preg = malloc(sizeof(regex_t))) == NULL) {
		fprintf(stderr, "Failed to malloc: %s\n", strerror(errno));
		return 1;
	}
	if(regcomp(preg, regex_str, REG_EXTENDED | REG_NOSUB) != 0) {
		fprintf(stderr, "Failed to complie regex\n");
		return 1;
	}
	if(regexec(preg, regex_src, 0, 0, 0) !=0)
		fprintf(stderr, "%s don't match %s\n", regex_src, regex_str);
	else
		fprintf(stderr, "match\n");
	return 0;
}

static void
parse_options(int argc, char **argv)
{
	extern char *optarg;
	extern int optind;
	int c;
	while((c=getopt(argc, argv, "r:s:v?"))!=-1) {
		switch(c) {
			case 'r' :
				regex_str = strdup(optarg);
				break;
			case 's' :
				regex_src = strdup(optarg);
				break;
			case 'v' :
				version();
				break;
			case '?' :
			default : 
				usage();
				break;
		}
	}
	if(optind < 5)
		usage();
}

static void 
version()
{
	fprintf(stderr, "%s\n", VERSION);
	exit(1);
}

static void 
usage()
{
	fprintf(stderr,
			"Usage: freeregex -r regex_char -s regex_source [-v?]\n"
			"       -r regex_char       Special regex char. For example '?{3}'\n"
			"       -s regex_source     Special regex source char.\n"
			"       -v                  Print version of regex_tester\n");
	exit(1);
}
